package arithmetic

import org.junit.jupiter.api.Test


/**
 * Created by jiangfeng on 2017/7/8.
 */
class TestMap {
    static void main(String[] args) {
        //  calculation2()
        expandParams(["a.b": 1])
    }

    @Test
    public void test() {
        expandParams(["a.b": 1])
    }
    /**
     * 将Map展开，便于数据绑定。
     *
     * <p>如 [ "a.b":1 ] 将转为 ["a": ["b":1]]。</p>
     */
    Map expandParams(Map params, boolean removeExpanded = true) {
        println 1
        List<String> keys = params.keySet().toList()
        for (String key in keys) {
            if (!key.contains(".")) continue
            List<String> expandKeys = key.tokenize(".")
            Map expandMap = params
            for (int i = 0; i < expandKeys.size(); i++) {
                String ekey = expandKeys[i]
                if (i < expandKeys.size() - 1) {
                    if (!expandMap.containsKey(ekey)) {
                        expandMap.put(ekey, [:])
                    }
                    if (expandMap.get(ekey) instanceof Map) {
                        // 此处比较精巧， 对expandMap进行了重新赋值空Map，并且地址和params用的是同一个。对expandMap改变也会改变元params
                        expandMap = (Map) expandMap.get(ekey)
                    } else break    // 冲突，不做处理
                } else {
                    expandMap.put(ekey, params.get(key))
                }
            }
            if (removeExpanded && expandMap.hashCode() != params.hashCode()) {
                params.remove(key)
            }
        }
        return params
    }
}